define(['bootstrapTable','layer','validate','md5','bootstrapTableTreegrid','jqueryTreegrid'],function (bootstrapTable,layer,validate,md5,bootstrapTreegrid,jqueryTreegrid) {
    $.validator.setDefaults({
        highlight: function (element) {
            $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
        },
        success: function (element) {
            element.closest('.form-group').removeClass('has-error').addClass('has-success');
        },
        errorElement: "span",
        errorPlacement: function (error, element) {
            if (element.is(":radio") || element.is(":checkbox")) {
                error.appendTo(element.parent().parent().parent());
            } else {
                error.appendTo(element.parent());
            }
        },
        errorClass: "help-block m-b-none",
        validClass: "help-block m-b-none"
    });
    return{
        init:function(){
            userTable();
            // submitUserForm();
            //查询
            $('.searchBtn').on('click',function () {
                $('#userTable').bootstrapTable("refresh");
            });

            //添加
            $('.addBtn').on('click',function () {
                $('#id').val(0);
                $('#userName').val("");
                $('#password').val("");
                $('#memberSelect').val("");// 部门名称
                $('#departmentId').val(0);// 部门id
                $("#treeview").hide();
                $('#verifyPassword').val("");
                $(".password").show();
                getDepartmentData(); // 部门
                getRoleData();// 角色
                openLayer('添加用户',$('#addUser'))
            });

            //保存
            $('#saveButton').on('click',function () {
                var id = $("#id").val();
                var url = "";
                var data = {};
                console.log(id);
                if(id == 0){ // 添加
                    url = '/loginUserController/add';
                    data = {
                        "loginName":$("#userName").val(),
                        "password":hex_md5($("#password").val()),
                        "verifyPassword":hex_md5($("#verifyPassword").val()),
                        "departId":$("#departmentId").val(),
                        "roleId":$("#roleSelect").val()
                    }
                }else { // 修改
                    url = '/loginUserController/update';
                    data = {
                        "id":id,
                        "loginName":$("#userName").val(),
                        "departId":$("#departmentId").val(),
                        "roleId":$("#roleSelect").val()
                    }
                }
                $.ajax({
                    url:url,
                    dataType:"json",
                    type:"post",
                    data:data,
                    success:function(result){
                        if(result.code == 10001){
                            layer.msg('保存成功', {icon: 1});
                            layer.closeAll();
                            $('#userTable').bootstrapTable("refresh");
                        }else{
                            layer.msg(result.msg, {icon: 2});
                        }
                    }
                })

            });
            $("#memberSelect").click(function(){
                $("#treeview").show()
            })


        }
    };
    // 部门下拉框
    function getDepartmentData(){
           $('#bootstrapTable').bootstrapTable({
               url:'/departmentController/pageSelect',
               method:'get',
               sidePagenation:'server',
               idField:'id',
               singleSelect:true,// 单选
               dataType:"json",
               clickToSelect:false,
               cache: false,       // 设置为 false 禁用 AJAX 数据缓存， 默认为true
               contentType:'application/x-www-form-urlencoded',
               queryParamsType : "",
               columns:[
                   {
                       field: 'ck',
                       checkbox: true,
                       width:'1%'
                   },{
                       field:'departmentName',
                       align: 'center',
                       valign: 'middle'
                       // title:'部门名称',
                       // width:'20%'
                   }
               ],
               treeShowField: 'departmentName',
               parentIdField: 'pId',
               onLoadSuccess: function(data) {
                   $("#bootstrapTable").treegrid({
                       initialState: 'expanded',//展开
                       treeColumn: 1,//指明第几列数据改为树形
                       expanderExpandedClass: 'fa fa-chevron-circle-down',
                       expanderCollapsedClass: 'fa fa-chevron-circle-right',
                       onChange: function() {
                           $("#bootstrapTable").bootstrapTable('resetWidth');
                           var data = $("#bootstrapTable").bootstrapTable('getSelections');
                           console.log(data);
                           $("#memberSelect").val(data[0].departmentName);
                           $("#departmentId").val(data[0].id);
                           $("#bootstrapTable").bootstrapTable('uncheckAll');
                           $("#treeview").hide();
                       }
                   });
               }
           })
    }
    // 角色下拉框
    function getRoleData(){
        $.ajax({
            type: 'GET',
            async: false,
            url: '/sysRoleController/findAll',
            success: function (data, status) {
                $("#roleSelect").html("");
                var role = JSON.parse(data);
                var html = '<option value=""></option>';
                for (var i = 0; i < role.length; i++) {
                    html += '<option value="' + role[i].id + '">' + role[i].roleName + '</option>'
                }
                $("#roleSelect").html(html);
            }
        });
    }
    function submitUserForm() {
        $('.addBtn').on('click',function () {
            layer.open({
                type: 1,
                title:'新增用户',
                anim: 1,
                closeBtn:1,
                area: ['60%','60%'],
                content:$('#addUser'),
                success: function(layero,index){
                    $('.addBtn').blur();
                }
            });
        });
        $('.reset').on('click',function () {
            $('.addForm')[0].reset();
        });
        $("#addForm").validate({
            rules: {
                userName: {
                    required: true,
                    minlength: 2
                },
                password: {
                    required: true,
                    minlength: 5
                },
                verifyPassword: {
                    required: true,
                    minlength: 5,
                    equalTo: "#password"
                },
                realName: {
                    required: true,
                },
            },
            messages: {
                userName: {
                    required:"请输入您的用户名",
                    minlength:"用户名必须两个字符以上"
                },
                password: {
                    required:"请输入您的密码",
                    minlength:"密码必须5个字符以上"
                },
                verifyPassword: {
                    required: "请再次输入密码",
                    minlength:"密码必须5个字符以上",
                    equalTo:"两次输入的密码不一致"
                },
                realName: {
                    required:"必须填写真实的姓名"
                }
            },
            submitHandler:function () {
                layer.msg('可以提交了',{icon:2})
            }
        });
    }
    function userTable() {
        var tableId=$('#userTable');
        window.openEvent={
            'click #editor':function (e,value,row,index) {

                $.ajax({
                    url:"/loginUserController/findById",
                    dataType:"json",
                    type:"post",
                    data:{
                        "id":row.id
                    },
                    success:function(result){
                        var data = result.data;
                        //回显
                        $("#id").val(data.id);
                        $("#userName").val(data.loginName);
                        $(".password").hide();
                        getDepartmentData(); // 部门
                        getRoleData();// 角色
                        $("#roleSelect").val(data.roleId);
                        $("#departmentId").val(data.departId);
                        $("#memberSelect").val(data.departName);
                        openLayer('修改用户',$("#addUser"));
                    }
                });
            },
            'click #delete':function (e,value,row,index) {
                layer.confirm('您确定要删除此用户？', {title:'删除用户信息',icon: 2,
                    btn: ['确定','取消'] //按钮
                }, function(){
                    $.ajax({
                        url:"/loginUserController/delete",
                        dataType:"json",
                        type:"post",
                        data:{
                            "id":row.id
                        },
                        success:function(result){
                            if(result.code == 10001){
                                layer.msg('删除成功', {icon: 1});
                                layer.closeAll();
                                $('#userTable').bootstrapTable("refresh");
                            }
                        }
                    })
                    layer.close();
                });
            }
        };
        tableId.bootstrapTable({
            url:'/loginUserController/pageSelect',
            method:'post',
            cache: false,       // 设置为 false 禁用 AJAX 数据缓存， 默认为true
            striped: true,      //表格显示条纹，默认为false
            pagination: true,   // 在表格底部显示分页组件，默认false
            contentType:'application/x-www-form-urlencoded',
            sidePagination: 'server', // 设置为服务器端分页，必要
            queryParamsType : "",
            queryParams:function(params){
                return tem={
                    rows:params.pageSize,
                    page:params.pageNumber,
                    loginName:$("#loginName").val()
                }
            },
            clickToSelect:false,
            columns: [
                {
                    title: '序号',
                    align: 'center',
                    formatter:showNumber,
                    width:'1%'
                },
                {
                    checkbox : true,
                    valign: 'middle',
                    width:'0.5%'
                },
                {
                    field: 'loginName',
                    title: '登录账号',
                    align: 'center',
                    valign: 'middle',
                    width:'25%'

                }, {
                    field: 'loginTime',
                    title: '最近登录时间',
                    align: 'center',
                    valign: 'middle',
                    width:'25%',
                    formatter:function (value,row,index) {
                        return fmtDate(value);
                    }
                }
                , {
                    field: 'roleName',
                    title: '角色',
                    align: 'center',
                    valign: 'middle',
                    width:'20%'
                }
                , {
                    field: 'departName',
                    title: '部门',
                    align: 'center',
                    valign: 'middle',
                    width:'20%'
                }
                , {
                    field:'operator',
                    title: "操作",
                    align: 'center',
                    valign: 'middle',
                    width:'10%',
                    events:openEvent,
                    formatter:function(value, row, index){
                        return ['<button class="btn btn-xs btn-info btn-operator-gew" id="editor"><i class="fa fa-edit"></i></button>','<button class="btn btn-xs btn-danger" id="delete"><i class="fa fa-trash-o"></i></button>'].join("");
                    }
                }
            ],
            onLoadSuccess: function(data){  //加载成功时执行
                //console.log(data);
            },
            onLoadError: function(){  //加载失败时执行
                //console.info("加载数据失败");
            }
            });
        };
    function queryParams(params) {
        var text=$.trim($('input[name="searchUser"]').val());
        var temp = {rows:params.pageSize,page:params.pageNumber,searchText:text};
        return temp;
    }
    function showNumber(value, row, index){
        var options = $('#userTable').bootstrapTable('getOptions');
        return options.pageSize*(options.pageNumber-1)+index + 1;
    }
    //时间戳转换
    function fmtDate(obj){
        if(obj == null){
            return null
        }
        var date = new Date(obj);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
        Y = date.getFullYear() + '-';
        M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
        D = (date.getDate()< 10 ? '0'+(date.getDate()): date.getDate()) + ' ';
        h = (date.getHours()< 10 ? '0'+(date.getHours()): date.getHours()) + ':';
        m = (date.getMinutes()< 10 ? '0'+(date.getMinutes()): date.getMinutes()) + ':';
        s = (date.getSeconds()< 10 ? '0'+(date.getSeconds()): date.getSeconds());
        return Y+M+D+h+m+s;
    }
    function openLayer(title,$dom){
        layer.open({
            type: 1,
            title:title,
            anim: 2,
            closeBtn:1,
            zIndex:500,
            area:["60%","80%"],
            content:$dom,
            end:function () {
                // location.reload();
            },
            cancel: function(index, layero){
                $dom.css({"display":"none"})
            }
        });
    }
});